package event

import (
	"fmt"
	"sync"
)

// Bus 事件总线结构体
type Bus struct {
	mu          sync.RWMutex
	subscribers map[string][]chan interface{}
}

// NewEventBus 创建新的事件总线
func NewEventBus() *Bus {
	return &Bus{
		subscribers: make(map[string][]chan interface{}),
	}
}

// Subscribe 订阅某个类型的事件
func (bus *Bus) Subscribe(key string) <-chan interface{} {
	bus.mu.Lock()
	defer bus.mu.Unlock()

	ch := make(chan interface{}, 15) // 缓冲 channel，避免阻塞
	bus.subscribers[key] = append(bus.subscribers[key], ch)
	return ch
}

// Unsubscribe 取消订阅
func (bus *Bus) Unsubscribe(evt string, ch <-chan interface{}) {
	bus.mu.Lock()
	defer bus.mu.Unlock()

	if subscribers, found := bus.subscribers[evt]; found {
		for i, subscriber := range subscribers {
			if subscriber == ch {
				close(subscriber)
				bus.subscribers[evt] = append(subscribers[:i], subscribers[i+1:]...)
				break
			}
		}
	}
}

// Publish 发布事件
func (bus *Bus) Publish(key string, obj interface{}) {
	bus.mu.RLock()
	defer bus.mu.RUnlock()

	if subscribers, found := bus.subscribers[key]; found {
		for _, ch := range subscribers {
			select {
			case ch <- obj:
			default:
				fmt.Printf("Warning: subscriber channel full, event dropped: %v, %v\n", key, obj)
			}
		}
	}
}
